import os
import sys
import time
import psutil
import json
import datetime
import psycopg2
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from tools.statistical_window import Statistical
# from apscheduler.schedulers.blocking import BlockingScheduler


class ProjectList(QListWidget):
    project_data_Signal=pyqtSignal(dict)
    def __init__(self):
        super(ProjectList, self).__init__()

        self.doubleClicked.connect(self.choose_project)


    def create_items(self,data_list):
        if data_list:
            self.clear()
            for i in data_list:
                full_name=i['full_name']
                entity_name=i['entity_name']
                # project_name=full_name+'('+entity_name+')'
                project_name = entity_name + '(' + full_name + ')'
                color=i['color']
                item=QListWidgetItem()
                item.setData(5,i)
                item.setText(project_name)
                item.setTextAlignment(Qt.AlignLeft)
                item.setBackground(QBrush(QColor(color)))
                self.addItem(item)
            self.sortItems()

    def choose_project(self,index):
        select_item=self.itemFromIndex(index)
        data=select_item.data(5)
        # print('choose_project:',data)
        self.project_data_Signal.emit(data)


    def filter_item(self,text):
        try:
            item_list=[]
            for i in range(self.count()):
                item=self.item(i)
                project_name=item.text()
                if text not in project_name:
                    item.setHidden(True)

        except Exception as filter_item_ERR:
            print('filter_item_ERR:',str(filter_item_ERR))

    def show_all(self):
        for i in range(self.count()):
            item = self.item(i)
            item.setHidden(False)


class ProjectWindow(QWidget):
    database_Signal=pyqtSignal(dict)
    def __init__(self):
        super(ProjectWindow, self).__init__()
        self.setWindowFlags(Qt.WindowStaysOnTopHint)

        self.data_list=[]  #查询到的所有项目信息列表
        self.setWindowTitle('选择项目,双击选择')
        self.main_layout=QVBoxLayout()
        self.show_label=QLabel('项目列表')
        self.search_layout=QHBoxLayout()
        self.search_edit=QLineEdit()
        self.search_edit.textEdited.connect(self._worktime_edited)
        self.search_btn=QPushButton('搜索')
        # self.search_btn.setShortcut(Qt.Key_Return|Qt.Key_Enter)
        self.search_btn.setShortcut(Qt.Key_Return)
        # self.search_btn.setShortcut(Qt.Key_Enter)
        self.search_btn.clicked.connect(self._search)
        # seach_icon=QIcon()
        # seach_icon.addPixmap(QPixmap(os.path.join(self.IMG_PATH,'ss.png')))
        # self.search_btn.setIcon(seach_icon)
        self.search_layout.addWidget(self.search_edit)
        self.search_layout.addWidget(self.search_btn)
        self.project_list=ProjectList()
        self.project_list.project_data_Signal.connect(self._get_project_data)
        self.init_project_list()
        self.main_layout.addWidget(self.show_label)
        self.main_layout.addLayout(self.search_layout)
        self.main_layout.addWidget(self.project_list)

        self.setLayout(self.main_layout)

    def init_project_list(self):

        try:
            time_connect = psycopg2.connect(database='postgres',
                                          user='timeaxis',
                                          password='timeaxis',
                                          host='192.168.1.222',
                                          port=5432)
            time_cursor = time_connect.cursor()
            select_sql = "select database,entity_name,full_name,color,frame_rate from timeaxis.r_project where status not in ('Close')"
            try:
                time_cursor.execute(select_sql)
                result=time_cursor.fetchall()
                data_list=[]
                unproject={}
                unproject['database'] = ''
                unproject['entity_name'] = 'NoProject'
                unproject['full_name'] = '非制作项目'
                unproject['color'] = '#808080'
                unproject['frame_rate'] = '0'
                data_list.append(unproject)
                if result:
                    for i in result:
                        data={}
                        data['database']=i[0]
                        data['entity_name']=i[1]
                        data['full_name']=i[2]
                        data['color']=i[3]
                        data['frame_rate']=i[4]
                        data_list.append(data)
                if data_list:
                    self.create_items(data_list)
                    self.data_list=data_list

            except Exception as sql_ERR:
                print('sql_ERR:',str(sql_ERR))
            finally:
                time_connect.close()
        except Exception as init_project_list_ERR:
            print('init_project_list_ERR:',str(init_project_list_ERR))

    def create_items(self,data_list):
        if data_list:
            self.project_list.create_items(data_list)

    def _worktime_edited(self,ha):
        if not ha:  #当没有搜索内容时，就重置
            # self.create_items(self.data_list)
            self.project_list.show_all()

    def _search(self):
        """
        搜索内容
        :return:
        """
        text=self.search_edit.text()
        if text:
            self.project_list.filter_item(text)

    def _get_project_data(self,data):
        """
        获取到选择的项目，之后开始配置该项目的数据
        :param data:
        :return:
        """
        self.database_Signal.emit(data)
        print(data)
        self.close()


class TaskListModel(QListWidget):
    send_daily_Signal=pyqtSignal(list)  #今日任务或者我的任务添加给今日进度表的数据
    data_info_Signal=pyqtSignal(dict)   #点击今日进度表中的item显示该任务的信息
    delete_task_Signal=pyqtSignal(list)  #daily中已分配右键删除的任务
    def __init__(self,list_type):
        super(TaskListModel, self).__init__()
        # self.is_daily=is_daily  #是否为今日进度列表,如果是那么有删除功能,没有添加功能
        self.list_type=list_type   #list_type:类型，当为origin_task时，即为可添加到今日分配任务的list,当为daily_task即今日提交任务，
        # 当为noworktime_task时，即为没工时的任务
        self.save_data_list=[]   #今日进度表中的任务列表经过编辑过后的信息
        self.setMinimumWidth(250)
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.setContextMenuPolicy(Qt.CustomContextMenu)  # 开启自定义右击菜单
        self.customContextMenuRequested.connect(self.right_menu)
        # self.setMaximumWidth(250)
        # self.setGridSize(QSize(1,1))
        # self.setLineWidth(5)
        # self.setWrapping(1)
        # self.setWordWrap(1)

        self.clicked.connect(self._show_data_info)

    def init_daily_data(self,data_list):
        """
        从本地daily数据库中初始化列表数据, 对今日进度列表进行初始化,用在切换日期进行更改时调用
        :param data: [{'id':xx,'task_type':xx,'date':xx,'project':xxx,'show_name':xx,'work_time':xx,'note':xxx,'color':xxx},...]
        :return:
        """

        if data_list:
            for i in data_list:
                item = QListWidgetItem()
                # item.setText(i['show_name']+'  制作时长  {}'.format(i['worktime']))
                # item.setText(i['show_name'] + ' | {} | {}'.format(i['date'], i['worktime']))
                # item.setText('{} | {} | {}'.format(i['date'], i['show_name'], i['worktime']))
                text = '{} | {} | {}'.format(i['date'], i['show_name'], i['worktime'])
                text = text[:21] + '\n' + text[21:]
                item.setText(text)
                item.setSizeHint(QSize(100, 35))
                item.setTextAlignment(Qt.AlignCenter)
                item.setBackground(QBrush(QColor(i['color'])))
                item.setData(5,i)
                self.addItem(item)

    def init_new_data(self,data_list):
        """
        初始化从排期数据库传来的任务列表,今日任务与我的任务
        :param data_list: [{}]
        :return:
        """
        self.clear()
        for i in data_list:
            # print('i.keys()',i)
            #print('status:',i['task_type'],i['status'],i['color'])
            # status='Wait' # i['status'] if i['task_type']=='cgtw' else 'Wait'
            item=QListWidgetItem()
            # item.setText(i['show_name'])
            text='{} | {} | {}'.format(i['date'], i['show_name'] ,i['show_workhour'])#i['worktime']

            text=text[:21]+'\n'+text[21:]
            item.setText(text)

            item.setSizeHint(QSize(100, 35))
            item.setTextAlignment(Qt.AlignCenter)
            color=self.get_color(i['task_type'],i['status'],i['color'])
            item.setData(5,i)
            item.setBackground(QBrush(QColor(color)))
            self.addItem(item)
        self.sortItems()


    def right_menu(self):
        rMenu = QMenu()
        addAction=QAction('添加到今日进度',self)
        addAction.triggered.connect(self._add_selected)
        deleteAction=QAction(u'删除',self)
        deleteAction.triggered.connect(self._delete_selected)
        if self.list_type=='origin_task':
            rMenu.addAction(addAction)
        elif self.list_type=='daily_task':
            rMenu.addAction(deleteAction)
        rMenu.exec_(QCursor.pos())

    def check_repeat(self,show_name):
        """
        检测重名
        #parm:artist
        """
        no_repeat=True
        all_count=self.count()
        # print('all_count:',all_count)
        if all_count>0:
            for i in range(all_count):
                item=self.item(i)
                if item.data(5)['show_name']==show_name:
                    no_repeat= False
                    break
                else:
                    no_repeat= True
        else:
            no_repeat= True
        return no_repeat

    def get_color(self,task_type,status,color):
        """
        如果是cgtw类型,那么根据状态来显示颜色,如果是Wait状态,那么color就是项目颜色
        如果是自定义任务,那么直接根据颜色来显示
        :param task_type:
        :param status:
        :param color:
        :return:
        """
        task_color = {'Approve': '#32CD32', 'Check': '#FFA500', 'Retake': '#FF0000', 'Close': '#000000',
                      '暂定': '#3CB371', '': '#F5F5F5',
                      '客户通过': '#006400', '客户返修': '#EE00EE', 'Ready': '#7B68EE', '半成品': '#FA8072', '已换人': '#C0C0C0',
                      '坏账': '#191970', '单帧通过': '#FA8072','':'#FFFFFF'}  # 'Wait':'#FF69B4',不要wait
        last_color='#696969'
        if task_type=='cgtw':
            if status in task_color:
                last_color=task_color[status]
            elif status=='Wait':
                last_color=color

        elif task_type=='custom':
            last_color=color

        return last_color

    def add_tasks(self,task_data_list):
        for i in task_data_list:
            show_name=i['show_name']
            if self.check_repeat(show_name):
                item=QListWidgetItem()
                text = show_name+' | 0'
                text = text[:15] + '\n' + text[15:]
                item.setText(text)
                item.setSizeHint(QSize(100, 35))
                item.setTextAlignment(Qt.AlignCenter)
                item.setData(5,i)
                color=self.get_color(i['task_type'],i['status'],i['color'])
                item.setBackground(QBrush(QColor(color)))
                self.addItem(item)

    def _add_selected(self):
        """
        将选择的添加到今日进度列表
        :return:
        """
        data_list=[]
        for i in self.selectedItems():
            # print(i,'添加到今日进度表')
            data=i.data(5)
            data_list.append(data)
        self.send_daily_Signal.emit(data_list)

    def _delete_selected(self):
        """
        删除选择的任务,只对今日进度表有效果
        :return:
        """
        daily_taskid_list=[]
        items=self.selectedItems()
        if items:
            for i in items:
                data=i.data(5)
                if data['id']:
                    daily_taskid_list.append(data['id'])
                self.takeItem(self.indexFromItem(i).row())
        if daily_taskid_list:
            self.delete_task_Signal.emit(daily_taskid_list)


    def filter_item(self,text):
        try:
            # item_list=[]
            for i in range(self.count()):
                item=self.item(i)
                name=item.text()
                if text not in name:
                    item.setHidden(True)

        except Exception as filter_item_ERR:
            print('filter_item_ERR:',str(filter_item_ERR))

    def show_all(self):
        for i in range(self.count()):
            item = self.item(i)
            item.setHidden(False)

    def get_save_data(self):
        """
        获取当前今日进度标中所有的已经编辑过的数据信息
        :return:
        """
        no_project_list=[]
        all_data_list=[]
        for i in range(self.count()):
            item = self.item(i)
            data=item.data(5)
            all_data_list.append(data)
            if not data['project_shortname']:
                no_project_list.append(data['show_name'])
        if no_project_list:
            QMessageBox.information(None,'错误','{}没有选择项目!'.format(no_project_list))
            return []
        else:
            return all_data_list

    def get_no_zero_data(self):
        """
        获取所有item中worktime不是0,且不是passtask类型的数据
        :return:
        """
        all_data_list=[]
        for i in range(self.count()):
            item = self.item(i)
            data=item.data(5)
            worktime=data['worktime']
            pass_task=data['pass_task']
            if pass_task!=0 or worktime!='0':
                all_data_list.append(data)

        return all_data_list

    def check_notime_item(self):
        """
        检测当前所有item是否有没有填写工时的任务
        :return:
        """
        notime_list=[]
        for i in range(self.count()):
            item = self.item(i)
            data=item.data(5)
            worktime=data['worktime']
            pass_task=data['pass_task']
            if pass_task==0 and worktime=='0':
                notime_list.append(data)
        if notime_list:
            return True
        else:
            return False

    def get_all_data(self):
        """
        获取当前表中所有的数据信息
        :return:
        """

        all_data_list=[]
        for i in range(self.count()):
            item = self.item(i)
            data=item.data(5)
            all_data_list.append(data)
        return all_data_list

    def update_item_data(self,data):
        """
        将
        :param data: 将当前数据注入到当前选择的item的data里
        :return:
        """
        items=self.selectedItems()
        if items:
            item=items[-1]
            ori_data=item.data(5)
            new_text=ori_data['show_name']+'  制作时长  {}'.format(data['worktime'])
            text = new_text[:21] + '\n' + new_text[21:]
            item.setText(text)
            client_count=ori_data['client_status_retake_count']
            if client_count>0:  #如果客户返修次数大于0，那么该次工时填写就录入到client_worktime里
                data['client_worktime']=data['worktime']
                # data['worktime']=0
            ori_data.update(data)
            item.setData(5,ori_data)


    def _show_data_info(self,index):
        item=self.itemFromIndex(index)
        data=item.data(5)
        data['item']=item   #把自身item也传进去
        self.data_info_Signal.emit(data)



class CheckFillin(object):
    def __init__(self):
        super(CheckFillin, self).__init__()
        self.date = time.strftime("%Y-%m-%d")
        self.artist,self.department = self.get_artist_by_ip()

    def _init_taskprogress_db(self):
        """
        创建一个操作本地_init_taskprogress_db数据库的临时连接
        :return:
        """
        try:
            time_connect = psycopg2.connect(database='taskprogress',
                                          user='timeaxis',
                                          password='timeaxis',
                                          host='192.168.1.222',
                                          port=5432)
            time_cursor = time_connect.cursor()
        except Exception as _init_taskprogress_db_ERR:
            print('_init_taskprogress_db_ERR:',str(_init_taskprogress_db_ERR))
            return None, None
        return time_connect, time_cursor

    def get_ip(self,prefix):
        """
        通过给定前缀跨平台查询ip
        :param prefix:
        :return:
        """
        localIP = ''
        dic = psutil.net_if_addrs()
        for adapter in dic:
            snicList = dic[adapter]
            for snic in snicList:
                if not snic.family.name.startswith('AF_INET'):
                    continue
                ip = snic.address
                if ip.startswith(prefix):
                    localIP = ip

        return localIP

    def get_artist_by_ip(self):

        ip = self.get_ip('192.168.1.')
        artist=''
        department=''
        if ip:
            sql = "select artist,department from account where ip = '{}'".format(ip)
            time_connect, time_cursor = self._init_taskprogress_db()
            try:
                time_cursor.execute(sql)
                result = time_cursor.fetchone()
                if result:
                    # print(result)
                    artist = result[0]
                    department=result[1]
                    # print(artist)
            except Exception as get_artist_by_ip_ERR:
                print('get_artist_by_ip_ERR:', str(get_artist_by_ip_ERR))
            finally:
                time_connect.close()
        return artist,department

    def _check_yesterday(self):
        """
        检测昨天有没有填写
        :return:
        """
        filled=False
        time_connect, time_cursor=self._init_taskprogress_db()
        yesterday=self.dateAdd(self.date,-1)
        y_sql="select * from note where artist='{}' and date='{}'".format(self.artist,yesterday)
        try:
            time_cursor.execute(y_sql)
            result=time_cursor.fetchone()
            if result:
                filled=True
        except Exception as _check_yesterday_ERR:
            print('_check_yesterday_ERR:',str(_check_yesterday_ERR))
        finally:
            time_connect.close()

        return filled

    def _check_totody(self):
        """
        检测今天有没有填写
        :return:
        """
        filled=False
        time_connect, time_cursor=self._init_taskprogress_db()

        t_sql="select * from note where artist='{}' and date='{}'".format(self.artist,self.date)
        try:
            time_cursor.execute(t_sql)
            result=time_cursor.fetchone()
            if result:
                filled=True
        except Exception as _check_yesterday_ERR:
            print('_check_totody_ERR:',str(_check_yesterday_ERR))
        finally:
            time_connect.close()

        return filled

    def dateAdd(self,start_date,days):
        """
        最正确的日期加法
        :param start_date:
        :param days:
        :return:
        """
        d=datetime.datetime.strptime(start_date,'%Y-%m-%d')
        delta = datetime.timedelta(days=days)
        n_days = d + delta
        return (n_days.strftime('%Y-%m-%d'))


class TP(QWidget):

    def __init__(self):
        super(TP, self).__init__()

        self.date =time.strftime("%Y-%m-%d")#'2020-09-15' #
        self.imgs_path=os.path.join(os.path.dirname(__file__),'imgs')
        self.nicon = QIcon(os.path.join(self.imgs_path,'n.png'))
        self.yicon = QIcon(os.path.join(self.imgs_path,'y.png'))
        self.setWindowIcon(self.yicon)
        self.big_font=QFont('',25,65)
        self.mid_font=QFont('',15,65)
        self.lit_font=QFont('',10,65)
        self.current_item=None   #当前选择的item,用来反向设置信息
        palette = QPalette()
        palette.setColor(palette.Background, QColor('#B0C4DE'))
        # ramp='qconicalgradient(cx:0, cy:0, angle:135, stop:0 rgba(242, 242, 242, 169), stop:0.375 rgba(222, 222, 222, 169), stop:0.423533 rgba(222,222,222, 145), stop:0.45 rgba(222 222, 222, 208), stop:0.477581 rgba(222 222, 222, 130), stop:0.518717 rgba(222, 222 222, 130), stop:0.55 rgba(222, 222, 222, 255), stop:0.57754 rgba(222, 222, 222, 130), stop:0.625 rgba(222, 222,222, 169), stop:1 rgba(222, 222, 222, 169))'
        self.ramp='qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1,stop: 0 rgb(242,242,242), stop: 1.0 rgb(180,180,180))'
        self.setStyleSheet('background:{}'.format(self.ramp))

        # eidt_style='QLineEdit{background}'
        self.show_btn_style = '''QPushButton{color:black}
                                  QPushButton:hover{color:#FF8C00}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:5px 10px}'''

        self.btn_style='''QPushButton{color:black}
                                  QPushButton:hover{color:red}
                   
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:5px 10px}'''
        #               QPushButton{background-color:#FFDEAD}
        self.submitbtn_style='''QPushButton{color:black}
                                  QPushButton:hover{color:red}
                        
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:10px}
                                  QPushButton{padding:5px 10px}'''
        #          QPushButton{background-color:#FFDEAD}
        self.freshbtn_style='''QPushButton{color:black}
                                  QPushButton:hover{color:red}
                  
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:10px}
                                  QPushButton{padding:5px 10px}'''
        #                QPushButton{background-color:	#C1CDCD}
        self.comb_style='''QComboBox{color:black}
                                  QComboBox:hover{color:red}
                                  
                                  QComboBox{border:2px}
                                  QComboBox{border-radius:3px}
                                  QComboBox{padding:1px 1px}'''

        self.artist,self.department=self.get_artist_by_ip()#'蔡宝润'#self.get_artist_by_ip()#'王颤颤'#  #初始化获取艺术家名称,获取公告栏信息
        # self.artist, self.department ='高馨雨','01美术'  #'邹季财','07特效二' #'蔡宝润','05场景'
        self.r_id_tasks_map={}  #r_id映射表，查询该r_id任务的已制作worktime总用时
        self.notice=self.get_notice()   #获取公告
        self.setWindowTitle('每日进度反馈')
        # self.setWindowFlags(Qt.FramelessWindowHint|Qt.WindowStaysOnTopHint)
        self.main_layout=QVBoxLayout()
        # self.main_layout.setAlignment(Qt.AlignLeft)
        self.content_layout=QHBoxLayout()
        self.content_layout.setAlignment(Qt.AlignLeft)
        self.content_layout.setContentsMargins(0,0,0,100)
        self.content_layout.setSpacing(30)
        #self.desktop=QApplication.desktop()
        #self.setMinimumWidth(self.desktop.width() if self.desktop.width()>1960 else 1960)
        #self.setMinimumHeight(self.desktop.height())
        self.label_layout=QHBoxLayout()
        self.label_layout.setAlignment(Qt.AlignCenter)
        self.label_layout.setContentsMargins(0,50,0,0)
        # self.show_label=QLabel('今日进度')
        # self.show_label.setFont(self.big_font)
        # self.label_layout.addWidget(self.show_label)
        self.show_btn=QPushButton('任务记录')
        self.show_btn.setFont(self.big_font)
        self.show_btn.setStyleSheet(self.show_btn_style)
        self.show_btn.clicked.connect(self._open_statistical_window)
        self.label_layout.addWidget(self.show_btn)


        self.left_layout=QVBoxLayout()
        self.left_layout.setAlignment(Qt.AlignLeft)
        # self.left_layout.setContentsMargins(-1350,0,0,0)
        self.today_layout=QVBoxLayout()
        self.today_layout.setContentsMargins(20, 30, 0, 30)
        self.today_layout.setSpacing(10)
        self.today_label=QLabel('今日任务')
        self.today_label.setFont(self.mid_font)
        self.today_label.setAlignment(Qt.AlignCenter)
        self.today_layout.setAlignment(Qt.AlignCenter)
        self.today_task_list=TaskListModel('origin_task')
        self.today_task_list.send_daily_Signal.connect(self._add_daily_task)
        self.today_layout.addWidget(self.today_label)
        self.today_layout.addWidget(self.today_task_list)
        self.my_task_layout=QVBoxLayout()
        # self.my_task_layout.setContentsMargins(0, 30, 0, 0)
        self.my_task_layout.setAlignment(Qt.AlignCenter)
        self.my_task_layout.setSpacing(10)
        self.my_task_label=QLabel('本月任务')
        self.my_task_label.setAlignment(Qt.AlignCenter)
        self.my_task_label.setFont(self.mid_font)
        self.my_task_search_layout=QHBoxLayout()
        # self.my_task_search_layout.setContentsMargins(10,0,150,0)
        self.my_task_edit=QLineEdit()
        self.my_task_edit.setStyleSheet('background: #F5F5F5')
        self.my_task_edit.setMaximumWidth(200)
        self.my_task_edit.textEdited.connect(self._task_edited)
        self.my_task_btn=QPushButton('筛选')
        self.my_task_btn.setShortcut(Qt.Key_Return)
        self.my_task_btn.setStyleSheet(self.btn_style)
        self.my_task_btn.clicked.connect(self._filter_my_task)
        self.my_task_btn.setMaximumWidth(50)
        self.my_task_search_layout.addWidget(self.my_task_edit)
        self.my_task_search_layout.addWidget(self.my_task_btn)
        self.my_task_list=TaskListModel('origin_task')
        self.my_task_list.send_daily_Signal.connect(self._add_daily_task)
        self.my_task_layout.addWidget(self.my_task_label)
        self.my_task_layout.addLayout(self.my_task_search_layout)
        self.my_task_layout.addWidget(self.my_task_list)
        self.left_layout.addLayout(self.today_layout)
        self.left_layout.addLayout(self.my_task_layout)

        self.mid_layout=QVBoxLayout()
        self.mid_layout.setAlignment(Qt.AlignLeft)
        self.mid_layout.setSpacing(10)
        # self.mid_layout.setContentsMargins(50,0,50,0)
        self.artist_label_layout=QHBoxLayout()
        self.artist_label_layout.setContentsMargins(0,30,0,0)
        self.artist_label_layout.setAlignment(Qt.AlignCenter)
        self.artist_label=QLabel('艺术家: {}'.format(self.artist))
        self.artist_label.setFont(self.mid_font)
        self.artist_label_layout.addWidget(self.artist_label)
        self.task_list=TaskListModel('daily_task')
        self.task_list.data_info_Signal.connect(self._show_info)
        self.task_list.delete_task_Signal.connect(self._delete_task)
        self.mid_layout.addLayout(self.artist_label_layout)
        self.mid_layout.addWidget(self.task_list)

        self.right_layout=QVBoxLayout()
        self.right_layout.setAlignment(Qt.AlignLeft)
        self.right_layout.setContentsMargins(0,35,0,0)
        self.date_layout=QHBoxLayout()
        self.date_layout.setSpacing(25)
        self.date_layout.setAlignment(Qt.AlignLeft)
        self.date_label=QLabel('日期:')
        self.date_label.setFont(self.lit_font)
        self.date_comb=QComboBox()
        self.date_comb.setStyleSheet(self.comb_style)
        self.date_comb.setMinimumWidth(150)
        self.init_date()
        self.date_comb.currentTextChanged.connect(self._change_date)
        self.update_btn=QPushButton('刷新')
        self.update_btn.setStyleSheet(self.freshbtn_style)
        self.update_btn.clicked.connect(self._update_all)
        self.date_layout.addWidget(self.date_label)
        self.date_layout.addWidget(self.date_comb)
        self.date_layout.addWidget(self.update_btn)
        self.count_layout=QHBoxLayout()
        self.count_label=QLabel('今日总工时:')
        self.count_label.setFont(self.lit_font)
        self.total_count_label=QLabel('0')
        self.count_layout.addWidget(self.count_label)
        self.count_layout.addWidget(self.total_count_label)
        self.task_info_frame=QFrame()
        self.task_info_layout=QVBoxLayout()
        self.task_info_layout.setSpacing(20)
        self.task_info_layout.setAlignment(Qt.AlignCenter)
        self.task_label=QLabel('任务信息')
        self.task_label.setAlignment(Qt.AlignCenter)
        self.task_label.setFont(self.mid_font)
        self.project_layout=QHBoxLayout()
        self.project_layout.setSpacing(25)
        self.project_layout.setAlignment(Qt.AlignLeft)
        self.project_label=QLabel('所属项目:')
        self.project_label.setFont(self.lit_font)
        self.project_btn=QPushButton('- -')
        # self.project_btn.setMinimumWidth(120)
        self.project_btn.setAutoFillBackground(True)
        self.project_btn.setStyleSheet(self.btn_style)
        self.project_btn.clicked.connect(self._open_project_window)
        self.project_layout.addWidget(self.project_label)
        self.project_layout.addWidget(self.project_btn)
        self.item_date_layout=QHBoxLayout()
        self.item_date_layout.setAlignment(Qt.AlignLeft)
        # self.item_date_layout.setSpacing(15)
        self.item_date_label=QLabel('填写日期:')
        self.item_date_label.setFont(self.lit_font)
        self.item_date=QLabel(self.date)
        # self.item_date.setAlignment(Qt.AlignLeft)
        self.item_date_layout.addWidget(self.item_date_label)
        self.item_date_layout.addWidget(self.item_date)
        self.taskprogress_layout=QHBoxLayout()
        self.taskprogress_layout.setAlignment(Qt.AlignLeft)
        self.taskprogress_assigned_label=QLabel('分配时长:')
        self.taskprogress_assigned_label.setFont(self.lit_font)
        self.taskprogress_assigned=QLabel('0')
        self.taskprogress_submitted_label = QLabel('已制作时长:')
        self.taskprogress_submitted_label.setFont(self.lit_font)
        self.taskprogress_submitted=QLabel('0')
        self.taskprogress_layout.addWidget(self.taskprogress_assigned_label)
        self.taskprogress_layout.addWidget(self.taskprogress_assigned)
        self.taskprogress_layout.addWidget(self.taskprogress_submitted_label)
        self.taskprogress_layout.addWidget(self.taskprogress_submitted)
        self.worktime_layout=QHBoxLayout()
        self.worktime_layout.setAlignment(Qt.AlignLeft)
        self.worktime_label=QLabel('制作时长:')
        self.worktime_label.setFont(self.lit_font)
        self.worktime_edit=QLineEdit()
        self.worktime_edit.setStyleSheet('background: #F5F5F5')
        self.worktime_edit.setPlaceholderText('单位小时')
        self.worktime_edit.textEdited.connect(self._worktime_edited)
        self.worktime_edit.setContentsMargins(0,0,80,0)
        self.worktime_unit_label=QLabel('/小时')
        self.worktime_unit_label.setAlignment(Qt.AlignLeft)
        self.passtask=QRadioButton('用时为0')
        self.passtask.clicked.connect(self._pass_task_changed)
        self.worktime_layout.addWidget(self.worktime_label)
        self.worktime_layout.addWidget(self.worktime_edit)
        self.worktime_layout.addWidget(self.passtask)
        #self.worktime_layout.addWidget(self.worktime_unit_label)

        self.task_note_layout=QHBoxLayout()
        self.task_note_label=QLabel('任务说明:')
        self.task_note_label.setFont(self.lit_font)
        self.task_note_text=QTextEdit()
        self.task_fix_btn=QPushButton('确认')
        self.task_fix_btn.setStyleSheet(self.btn_style)
        self.task_fix_btn.clicked.connect(self._confirm)

        self.evaluation_layout=QHBoxLayout()
        self.evaluation_layout.setSpacing(5)
        self.evaluation_layout.setAlignment(Qt.AlignLeft)
        self.evaluation_label = QLabel('任务评价:')
        self.evaluation_label.setFont(self.lit_font)
        self.score_layout=QVBoxLayout()
        self.assigned_layout=QHBoxLayout()
        self.assigned_layout.setAlignment(Qt.AlignLeft)
        self.assigned_layout.setSpacing(5)
        self.assigned_label=QLabel('安排合理度:')
        self.assigned_layout.addWidget(self.assigned_label)
        self.assigned_btns=self.init_toolbtn(self.assigned_layout,self._assinged_click)
        self.workhour_layout=QHBoxLayout()
        self.workhour_layout.setAlignment(Qt.AlignLeft)
        self.workhour_layout.setSpacing(5)
        self.workhour_label=QLabel('工时合理度:')
        self.workhour_layout.addWidget(self.workhour_label)
        self.workhour_btns=self.init_toolbtn(self.workhour_layout,self._workhour_click)
        self.score_layout.addLayout(self.assigned_layout)
        self.score_layout.addLayout(self.workhour_layout)
        self.evaluation_layout.addWidget(self.evaluation_label)
        self.evaluation_layout.addLayout(self.score_layout)
        self.evaluation_layout.addWidget(self.task_fix_btn)
        self.task_note_layout.addWidget(self.task_note_label)
        self.task_note_layout.addWidget(self.task_note_text)
        # self.task_note_layout.addWidget(self.task_fix_btn)
        self.task_info_layout.addWidget(self.task_label)
        self.task_info_layout.addLayout(self.project_layout)
        self.task_info_layout.addLayout(self.item_date_layout)
        self.task_info_layout.addLayout(self.taskprogress_layout)
        self.task_info_layout.addLayout(self.worktime_layout)
        self.task_info_layout.addLayout(self.task_note_layout)
        self.task_info_layout.addLayout(self.evaluation_layout)
        self.task_info_frame.setLayout(self.task_info_layout)
        self.note_layout=QVBoxLayout()
        self.note_layout.setSpacing(10)
        self.note_layout.setAlignment(Qt.AlignCenter)
        self.note_label=QLabel('备注')
        self.note_label.setFont(self.mid_font)
        self.note_label.setAlignment(Qt.AlignCenter)
        self.note_text=QTextEdit()
        self.note_layout.addWidget(self.note_label)
        self.note_layout.addWidget(self.note_text)
        self.btn_layout=QVBoxLayout()
        self.submit_btn=QPushButton('提交')
        self.submit_btn.setStyleSheet(self.submitbtn_style)
        self.submit_btn.setMinimumHeight(50)
        self.submit_btn.clicked.connect(self._submit)
        self.btn_layout.addWidget(self.submit_btn)
        self.right_layout.addLayout(self.date_layout)
        self.right_layout.addLayout(self.count_layout)
        self.right_layout.addWidget(self.task_info_frame)
        self.right_layout.addLayout(self.note_layout)
        self.right_layout.addLayout(self.btn_layout)

        self.zero_layout=QVBoxLayout()
        self.zero_layout.setAlignment(Qt.AlignLeft)
        self.zero_layout.setSpacing(10)
        self.zero_label_layout=QHBoxLayout()
        self.zero_label_layout.setContentsMargins(0,30,0,0)
        self.zero_label_layout.setAlignment(Qt.AlignCenter)
        self.zero_label=QLabel('未填写任务')
        self.zero_label.setFont(self.mid_font)
        self.zero_label_layout.addWidget(self.zero_label)
        self.zero_task_list=TaskListModel('noworktime_task')
        self.zero_task_list.data_info_Signal.connect(self._show_info)
        self.zero_task_list.delete_task_Signal.connect(self._delete_task)
        self.zero_layout.addLayout(self.zero_label_layout)
        self.zero_layout.addWidget(self.zero_task_list)


        self.notice_layout=QVBoxLayout()
        # self.notice_layout.setAlignment(Qt.AlignTop)
        self.notice_layout.setAlignment(Qt.AlignCenter)
        self.notice_layout.setContentsMargins(20, 0, 50, 0)
        self.notice_label=QLabel('公告栏')
        self.notice_label.setFont(self.mid_font)
        self.notice_label.setAlignment(Qt.AlignCenter)
        self.notice_do=QLabel(self.notice)
        self.notice_do.setAlignment(Qt.AlignCenter)

        self.explain_layout=QVBoxLayout()
        self.explain_layout.setSpacing(30)
        self.explain_layout.setContentsMargins(20,30,0,0)
        self.explain_layout.setAlignment(Qt.AlignTop)
        self.explain_label=QLabel()
        self.init_explain()

        self.help_label=QLabel('提交说明')
        self.help_label.setFont(self.mid_font)
        self.help_label.setContentsMargins(0,50,0,0)
        self.help_label.setAlignment(Qt.AlignCenter)
        self.help_do=QLabel('xxx')
        self.init_help()
        self.explain_layout.addWidget(self.explain_label)
        self.explain_layout.addWidget(self.help_label)
        self.explain_layout.addWidget(self.help_do)
        self.notice_layout.addWidget(self.notice_label)
        self.notice_layout.addWidget(self.notice_do)
        self.notice_layout.addLayout(self.explain_layout)

        self.main_layout.addLayout(self.label_layout)
        self.content_layout.addLayout(self.left_layout)
        self.content_layout.addLayout(self.mid_layout)
        self.content_layout.addLayout(self.right_layout)
        self.content_layout.addLayout(self.zero_layout)
        self.content_layout.addLayout(self.notice_layout)


        self.content_layout.setStretch(0,1)
        self.content_layout.setStretch(1,1)
        self.content_layout.setStretch(2,1)
        self.content_layout.setStretch(3,1)
        self.main_layout.addLayout(self.content_layout)
        self.setLayout(self.main_layout)
        self.project_map=self.init_project_map()
        # print('project_map:',self.project_map)
        self._update_all()  #打开就读取了今日信息

        self.assigned_score='5'
        self.workhour_score='5'

    def _open_statistical_window(self):
        """
        打开统计面板
        :return:
        """

        self.statistical_window=Statistical(self)
        self.statistical_window.show()


    def init_project_map(self):
        data = {}
        data['NoProject']='非制作项目'
        try:
            time_connect = psycopg2.connect(database='postgres',
                                          user='timeaxis',
                                          password='timeaxis',
                                          host='192.168.1.222',
                                          port=5432)
            time_cursor = time_connect.cursor()
            select_sql = "select database,entity_name,full_name,color,frame_rate from timeaxis.r_project where status not in ('Close')"
            try:
                time_cursor.execute(select_sql)
                result=time_cursor.fetchall()
                data_list=[]
                unproject={}
                unproject['database'] = ''
                unproject['entity_name'] = 'NoProject'
                unproject['full_name'] = '非制作项目'
                unproject['color'] = '#808080'
                unproject['frame_rate'] = '0'
                data_list.append(unproject)
                if result:
                    for i in result:
                        # data['database']=i[0]
                        data[i[1]]=i[2] #记录HYX: 中文名
                        # data['entity_name']=i[1]
                        # data['full_name']=i[2]
                        # data['color']=i[3]
                        # data['frame_rate']=i[4]
                        # data_list.append(data)
                # if data_list:
                #     self.project_map=data_list

            except Exception as sql_ERR:
                print('sql_ERR:',str(sql_ERR))
            finally:
                time_connect.close()
        except Exception as init_project_map_ERR:
            print('init_project_map_ERR:',str(init_project_map_ERR))
        print('init_project_map  data:',data)
        return data


    def pre_init(self):
        self.artist,self.department=self.get_artist_by_ip()


    def dateAdd(self,start_date,days):
        """
        最正确的日期加法
        :param start_date:
        :param days:
        :return:
        """
        d=datetime.datetime.strptime(start_date,'%Y-%m-%d')
        delta = datetime.timedelta(days=days)
        n_days = d + delta
        return (n_days.strftime('%Y-%m-%d'))


    def delta_date(self, start_date, end_date):
        """
        计算起始与结束日期长度，是结束-起始，所以一般为正。用做判定日期大小需要注意前后顺序
        :param start_date:
        :param end_date:
        :return:
        """
        start = datetime.datetime.strptime(start_date, "%Y-%m-%d")
        end = datetime.datetime.strptime(end_date, "%Y-%m-%d")
        delta_day = (end - start).days
        return delta_day


    def getEveryDay(self, start_date, end_date):
        date_list = []
        start = datetime.datetime.strptime(start_date, "%Y-%m-%d")
        end = datetime.datetime.strptime(end_date, "%Y-%m-%d")
        while start <= end:
            date_str = start.strftime("%Y-%m-%d")
            date_list.append(date_str)
            start += datetime.timedelta(days=1)
        return date_list


    def init_date(self):
        """
        初始化日期
        :return:
        """
        current_date=time.strftime("%Y-%m-%d")
        yestoday=self.dateAdd(current_date,-1)
        tday=self.dateAdd(current_date,-2)
        date_list=[tday,yestoday,current_date]
        self.date_comb.addItems(date_list)
        self.date_comb.setCurrentText(current_date)

    def _change_date(self,current_date):
        """
        改变了日期
        :return:
        """
        self.date=current_date  #一定要先更新日期,否则后面计算就错了
        self._update_all()
        worktimes=self.get_all_hour()
        self._set_total_label(worktimes)

    def init_explain(self):
        """
        解释说明
        :return:
        """
        explain='''
        为更有效估算项目进度，同时帮助艺术家们更好的\n评估制度难度与工时，实现更合理有效的工时分配，请大家\n配合认真填写今日任务进度信息，谢谢！。
        '''
        explain="<p style='line-height:100%'>&nbsp;&nbsp;为更有效估算项目进度，同时帮助艺术家们更好的</p><p style='line-height:100%'> 评估制度难度与工时，实现更合理有效的工时分配，请大家</p>" \
                "</p><p style='line-height:100%'> 配合认真填写今日任务进度信息，谢谢！</p>"
        self.explain_label.setText(explain)
        # self.explain_label.setStyleSheet('line-height:150%')

        # self.explain_label.setLineWidth(10)

    def init_help(self):
        help='1.选择日期，默认可选择3天内任务信息\n\n' \
             '2.今日任务,显示今日排期上的任务,选择后右键进行添加操作\n\n' \
             '3.本月任务,显示一个月内排期上的任务,选择后右键进行添加操作\n\n' \
             '4.中间艺术家栏,是今日所进行的任务,选择任务后在右边任务信息\n中进行工时编辑,如果是自定义任务需要选择对应项目\n\n' \
             '5.未填写任务,前半个月内没有填写制作时长的任务\n\n' \
             '6.备注,对未记录任务或者特殊情况进行备注说明\n\n' \
             '7.该任务没有制作或者本身不是制作任务的点上--用时为0'
        self.help_do.setText(help)


    def _init_taskprogress_db(self):
        """
        创建一个操作本地_init_taskprogress_db数据库的临时连接
        :return:
        """
        try:
            time_connect = psycopg2.connect(database='taskprogress',
                                          user='timeaxis',
                                          password='timeaxis',
                                          host='192.168.1.222',
                                          port=5432)
            time_cursor = time_connect.cursor()
        except Exception as _init_taskprogress_db_ERR:
            print('_init_taskprogress_db_ERR:',str(_init_taskprogress_db_ERR))
            return None, None
        return time_connect, time_cursor

    def _init_scheduler_db(self):
        """
        创建一个操作排期系统数据库的临时连接
        :return:
        """
        try:
            sche_connect = psycopg2.connect(database='postgres',
                                          user='timeaxis',
                                          password='timeaxis',
                                          host='192.168.1.222',
                                          port=5432)
            sche_cursor = sche_connect.cursor()
        except Exception as _init_scheduler_db_ERR:
            print('_init_scheduler_db_ERR:',str(_init_scheduler_db_ERR))
            return None, None
        return sche_connect, sche_cursor

    def get_ip(self,prefix):
        """
        通过给定前缀跨平台查询ip
        :param prefix:
        :return:
        """
        localIP = ''
        dic = psutil.net_if_addrs()
        for adapter in dic:
            snicList = dic[adapter]
            for snic in snicList:
                if not snic.family.name.startswith('AF_INET'):
                    continue
                ip = snic.address
                if ip.startswith(prefix):
                    localIP = ip

        return localIP


    def get_artist_by_ip(self):
        # artist=''
        # myname = socket.getfqdn(socket.gethostname())
        # # print(myname)

        ip=self.get_ip('192.168.1.')
        artist=''
        department=''
        if ip:
            sql ="select artist,department from account where ip = '{}'".format(ip)
            time_connect, time_cursor=self._init_taskprogress_db()
            try:
                time_cursor.execute(sql)
                result=time_cursor.fetchone()
                if result:
                    # print(result)
                    artist=result[0]
                    department=result[1]
                    print(artist)
            except Exception as get_artist_by_ip_ERR:
                print('get_artist_by_ip_ERR:',str(get_artist_by_ip_ERR))
            finally:
                time_connect.close()
        return artist,department

    def get_notice(self):
        notice=''
        sql ="select notice from config where id = 1"
        time_connect, time_cursor=self._init_taskprogress_db()
        try:
            time_cursor.execute(sql)
            result=time_cursor.fetchone()
            if result:
                # print(result)
                notice=result[0]
                print(notice)
        except Exception as get_notice_ERR:
            print('get_notice_ERR:',str(get_notice_ERR))
        finally:
            time_connect.close()
        return notice


    def get_project_shotname(self,name):
        shotname=''
        if name:
            if '(' not in name:
                shotname=name
            else:
                shotname=name.split('(')[1][:-1]
        return shotname

    def get_alltask_by_date(self,artist,date):
        """
        根据所给定日期,获取排期系统上task表与custom_task表里对应的任务数据
        :param artist:  艺术家姓名
        :param date:
        :return:
        """
        data_list = []
        limit_start_date=self.dateAdd(date,-15)
        limit_end_date=self.dateAdd(date,15)
        date_list=self.getEveryDay(limit_start_date,limit_end_date)  #这里是我的任务日期范围,前后15天范围内的
        connect_dates='|'.join(date_list)
        try:
            #获取cgtw类型任务
            sche_connect, sche_cursor=self._init_scheduler_db()
            task_sql="select task_type,start_date,end_date,status,show_name,show_workhour,workhour,project_shortname," \
                 "department,project_color,id,client_status_retake_count,project_name from timeaxis.task where artist='{0}' and (start_date similar to '({1})' or end_date similar to '({1})') ".format(artist,connect_dates)

            sche_cursor.execute(task_sql)
            result=sche_cursor.fetchall()
            if result:
                for i in result:
                    # print(i)
                    data={}
                    data['id']=''  #初始化任务,默认id为空,表示非已分配daily表中任务
                    data['task_type']=i[0]
                    data['start_date']=i[1]
                    data['end_date'] = i[2]
                    data['status']=i[3]
                    data['show_name']=i[4]
                    data['show_workhour'] = i[5]
                    data['workhour']=i[6]
                    data['project_shortname']=i[7]
                    data['department'] = i[8]
                    data['project_color']=i[9]
                    data['color'] = i[9]  #取通用字段名color
                    data['r_id']=i[10]
                    data['client_status_retake_count'] = i[11]  #客户返修任务用来分开记录工时录入
                    data['full_name']=i[12]  #task表里的project_name是 中文名(简称)
                    data['artist']= artist
                    data['worktime']='0'  #初始化任务信息将worktime字段加进去
                    data['client_worktime'] = '0'  # 初始化任务信息将client_worktime字段加进去
                    data['note']=''   #初始化将任务备注字段加进去
                    data['date']=self.date  #初始化加入当前date
                    data['assigned_score']='5'  #初始化安排合理度
                    data['workhour_score']='5'  #初始化工时合理度
                    data['pass_task']=0  #初始化是否为忽略任务
                    if data['start_date']==data['end_date']:  #非跨天任务
                        data['date']=data['start_date']
                        data_list.append(data)
                    else:   #跨天任务，拆成每个任务
                        task_date_list=self.getEveryDay(data['start_date'],data['end_date'])
                        data['show_workhour']=str(float( data['show_workhour'])/len(task_date_list))  #将每个任务按长度均分
                        for d in task_date_list:
                            sperate_data={}
                            for k,v in data.items():
                                sperate_data[k]=v   #复制data
                            sperate_data['date'] = d
                            data_list.append(sperate_data)

                    # data_list.append(data)
            print('get_alltask_by_date 002')
            #获取自定义任务  过滤掉超时任务
            custom_sql="select start_date,end_date,show_name,show_workhour,project_name,department,color,id,workhour from " \
                       "timeaxis.custom_task where artist='{0}'and (start_date similar to '({1})' or end_date similar to '({1})') ".format(artist,connect_dates) # and custom_type !='超时'   超时认为不能过滤

            sche_cursor.execute(custom_sql)
            c_result=sche_cursor.fetchall()
            if c_result:
                for c in c_result:
                    # print('get_alltask_by_date 000',c)
                    data={}
                    data['id'] = ''  # 初始化任务,默认id为空,表示非已分配daily表中任务
                    data['task_type'] = 'custom'
                    data['start_date']=c[0]
                    data['end_date']=c[1]
                    data['show_name']=c[2]
                    # if data['show_name']=='HYX09_10_030-env':
                    #     print('HYX09_10_030-env找到了！！！！！！！')
                    data['show_workhour']=c[3]
                    # print('get_alltask_by_date 001.1',c[4])
                    data['project_shortname']=self.get_project_shotname(c[4])
                    # print('get_alltask_by_date 001.2', data['project_shortname'])
                    data['full_name'] = ''#初始化任务信息将project_name
                    data['department']=c[5]
                    data['color']=c[6]
                    # print('get_alltask_by_date 00c1')
                    data['r_id']=c[7]
                    data['workhour']=c[8]
                    data['client_status_retake_count']=0  #自定义任务默认客户返修次数为0
                    data['status']=''  #通用状态字段添加
                    data['artist']= artist
                    data['worktime']='0'  #初始化任务信息将worktime字段加进去
                    data['client_worktime'] = '0'  # 初始化任务信息将client_worktime字段加进去
                    data['note']=''   #初始化将任务备注字段加进去
                    # print('get_alltask_by_date 00c2')
                    data['date']=self.date  #初始化加入当前date
                    data['assigned_score'] = '5'  # 初始化安排合理度
                    data['workhour_score'] = '5'  # 初始化工时合理度
                    data['pass_task']= 0   #初始化是否为忽略任务
                    # data_list.append(data)
                    # print('get_alltask_by_date 003')
                    if data['start_date']==data['end_date']:  #非跨天任务
                        data['date'] = data['start_date']
                        data_list.append(data)
                    else:   #跨天任务，拆成每个任务
                        task_date_list=self.getEveryDay(data['start_date'],data['end_date'])
                        data['show_workhour'] = str(float(data['show_workhour']) / len(task_date_list))
                        for p in task_date_list:
                            # print('get_alltask_by_date 005',p)
                            sperate_data={}
                            for k,v in data.items():
                                sperate_data[k]=v   #复制data
                            # print('get_alltask_by_date 006')
                            sperate_data['date'] = p
                            sperate_data['start_date']=p  #将起始日期变成该天
                            sperate_data['end_date'] = p   #将结束日期变成该天
                            data_list.append(sperate_data)
                            # print('get_alltask_by_date 007')
                        # print('get_alltask_by_date 007')
            # print('get_alltask_by_date 003')
        except Exception as get_task_by_date_ERR:
            print('get_task_by_date_ERR:',str(get_task_by_date_ERR))

        finally:
            sche_connect.close()

        return data_list

    def get_allSavedTask_by_oneMonthtask(self,data_list):
        """
        传入排期软件里查询的一个月的所有任务列表，再通过r_id来查询本地daily中的对应所有的任务，求出其已花费的工时
        :param data_list:
        :return:
        """
        r_id_tasks_map={}  #{'r_id':所有已用掉的工时,'r_id':xx}
        if data_list:
            r_id_list=[]
            for data in data_list:
                r_id=data['r_id']
                if r_id not in r_id_list:
                    r_id_list.append(r_id)
            time_connect, time_cursor = self._init_taskprogress_db()
            try:
                for i in r_id_list:
                    sql = "select sum(cast(worktime as float)) from daily where r_id={}".format(i)
                    time_cursor.execute(sql)
                    result = time_cursor.fetchone()
                    all_worktime=result[0] if result else 0
                    r_id_tasks_map[i]=all_worktime
            except Exception as get_allSavedTask_by_oneMonthtask_ERR:
                print(str(get_allSavedTask_by_oneMonthtask_ERR))
            finally:
                time_connect.close()
        print('r_id_tasks_map:',r_id_tasks_map)
        return r_id_tasks_map



    def get_alltask_by_range_date(self,artist,start_date,end_date):
        """
        根据所给定日期范围,获取排期系统上task表与custom_task表里对应的任务数据
        :param artist:  艺术家姓名
        :param date:
        :return:
        """
        data_list = []
        try:
            #获取cgtw类型任务
            sche_connect, sche_cursor=self._init_scheduler_db()
            task_sql="select task_type,start_date,end_date,status,show_name,show_workhour,workhour,project_shortname," \
                 "department,project_color,id,client_status_retake_count,project_name from timeaxis.task where artist='{0}' and start_date <= '{1}' and end_date >='{2}'".format(artist,end_date,start_date)

            sche_cursor.execute(task_sql)
            result=sche_cursor.fetchall()
            if result:
                for i in result:
                    # print(i)
                    data={}
                    data['id']=''  #初始化任务,默认id为空,表示非已分配daily表中任务
                    data['task_type']=i[0]
                    data['start_date']=i[1]
                    data['end_date'] = i[2]
                    data['status']=i[3]
                    data['show_name']=i[4]
                    data['show_workhour'] = i[5]
                    data['workhour']=i[6]
                    data['project_shortname']=i[7]
                    data['department'] = i[8]
                    data['project_color']=i[9]
                    data['color'] = i[9]  #取通用字段名color
                    data['r_id']=i[10]
                    data['client_status_retake_count'] = i[11]  #客户返修任务用来分开记录工时录入
                    data['full_name']=i[12]  #task表里的project_name是 中文名(简称)
                    data['artist']= artist
                    data['worktime']='0'  #初始化任务信息将worktime字段加进去
                    data['client_worktime'] = '0'  # 初始化任务信息将client_worktime字段加进去
                    data['note']=''   #初始化将任务备注字段加进去
                    data['date']=self.date  #初始化加入当前date
                    data['assigned_score']='5'  #初始化安排合理度
                    data['workhour_score']='5'  #初始化工时合理度
                    data['pass_task']=0  #初始化是否为忽略任务
                    if data['start_date']==data['end_date']:  #非跨天任务
                        data['date']=data['start_date']
                        data_list.append(data)
                    else:   #跨天任务，拆成每个任务
                        task_date_list=self.getEveryDay(data['start_date'],data['end_date'])
                        data['show_workhour']=str(float( data['show_workhour'])/len(task_date_list))  #将每个任务按长度均分
                        for d in task_date_list:
                            sperate_data={}
                            for k,v in data.items():
                                sperate_data[k]=v   #复制data
                            sperate_data['date'] = d
                            data_list.append(sperate_data)

                    # data_list.append(data)
            # print('get_alltask_by_range_date 002')
            #获取自定义任务  过滤掉超时任务
            custom_sql="select start_date,end_date,show_name,show_workhour,project_name,department,color,id,workhour from " \
                       "timeaxis.custom_task where artist='{0}'and start_date <= '{1}' and end_date >='{2}' ".format(artist,end_date,start_date) # and custom_type !='超时'   超时认为不能过滤

            sche_cursor.execute(custom_sql)
            # print('get_alltask_by_range_date 002.1')
            c_result=sche_cursor.fetchall()
            # print('get_alltask_by_range_date 002.3')
            if c_result:
                for c in c_result:
                    # print('get_alltask_by_range_date 000',c)
                    data={}
                    data['id'] = ''  # 初始化任务,默认id为空,表示非已分配daily表中任务
                    data['task_type'] = 'custom'
                    data['start_date']=c[0]
                    data['end_date']=c[1]
                    data['show_name']=c[2]
                    data['show_workhour']=c[3]
                    # print('get_alltask_by_range_date 001.1',c[4])
                    data['project_shortname']=self.get_project_shotname(c[4])
                    # print('get_alltask_by_range_date 001.2', data['project_shortname'])
                    data['full_name'] = ''#初始化任务信息将project_name
                    data['department']=c[5]
                    data['color']=c[6]
                    # print('get_alltask_by_range_date 00c1')
                    data['r_id']=c[7]
                    data['workhour']=c[8]
                    data['client_status_retake_count']=0  #自定义任务默认客户返修次数为0
                    data['status']=''  #通用状态字段添加
                    data['artist']= artist
                    data['worktime']='0'  #初始化任务信息将worktime字段加进去
                    data['client_worktime'] = '0'  # 初始化任务信息将client_worktime字段加进去
                    data['note']=''   #初始化将任务备注字段加进去
                    # print('get_alltask_by_range_date 00c2')
                    data['date']=self.date  #初始化加入当前date
                    data['assigned_score'] = '5'  # 初始化安排合理度
                    data['workhour_score'] = '5'  # 初始化工时合理度
                    data['pass_task']= 0   #初始化是否为忽略任务
                    # data_list.append(data)
                    # print('get_alltask_by_range_date 003')
                    if data['start_date']==data['end_date']:  #非跨天任务
                        data['date'] = data['start_date']
                        data_list.append(data)
                    else:   #跨天任务，拆成每个任务
                        task_date_list=self.getEveryDay(data['start_date'],data['end_date'])
                        data['show_workhour'] = str(float(data['show_workhour']) / len(task_date_list))
                        for p in task_date_list:
                            # print('get_alltask_by_range_date 005',p)
                            sperate_data={}
                            for k,v in data.items():
                                sperate_data[k]=v   #复制data
                            # print('get_alltask_by_range_date 006')
                            sperate_data['date'] = p
                            sperate_data['start_date']=p  #将起始日期变成该天
                            sperate_data['end_date'] = p   #将结束日期变成该天
                            data_list.append(sperate_data)
                            # print('get_alltask_by_range_date 007')
                        # print('get_alltask_by_range_date 007')
            # print('get_alltask_by_range_date 003')
        except Exception as get_task_by_date_ERR:
            print('get_task_by_date_ERR:',str(get_task_by_date_ERR))

        finally:
            sche_connect.close()

        return data_list


    def get_15_data(self,all_data,date):
        """
        通过传入get_alltask_by_date获取前后15天的所有任务(包括cgtw任务与自定义任务)，这里排除点今天以及今天之后的所有任务，只留半个月前的任务
        这里的任务要进行处理，如果不跨天，那么就是一个任务，如果跨天，那么就拆成对应天数的任务个数。
        :param all_data:
        :param date:
        :return:
        """
        half_month_tasks=[]
        if all_data:
            for data in all_data:
                # print('data[date]:',data['date'])
                start_date=data['start_date']
                end_date=data['end_date']
                # if data['r_id']==182576:
                #     print('182576:',data)
                if self.delta_date(start_date,date)>0: #已起始日期作为初判
                    half_month_tasks.append(data)  #现在每天任务的起始与结束日期一样，已经被拆分了
                    # if start_date==end_date:
                    #     half_month_tasks.append(data)
                    # else:
                    #     date_list=self.getEveryDay(start_date,end_date)
                    #     # print(data['show_name'],'date_list:',date_list)
                    #     for i in date_list:
                    #         sperate_data={}
                    #         for k,v in data.items():
                    #             sperate_data[k]=v   #复制data
                    #         sperate_data['date'] = i
                    #         half_month_tasks.append(sperate_data)

        return half_month_tasks


    def get_current_date_tasks(self,date,all_task_list):
        """
        根据给定的日期,来筛选出当日所占用的任务
        :param date:
        :param all_task_list:
        :return:
        """
        date_tasks=[]
        for i in all_task_list:
            # start_date=i['start_date']
            # end_date=i['end_date']
            # delta_start=self.delta_date(start_date,date)  #起始日期与给定日期差值 ,这里delta_date 都是后一个日期减去前一个日期
            # delta_end=self.delta_date(date,end_date)   #结束日期与给定日期差值
            # #当起始日期-给定日期<=0 且结束日期-给定日期>=0 才是跨今日的任务
            # if delta_start>=0 and delta_end>=0:
            #     date_tasks.append(i)

            if i['date']==date:
                date_tasks.append(i)


        return date_tasks

    def get_current_daily_tasks(self,date):
        """
        根据指定的日期,获取该艺术家daily中已经存入的任务,以及当日的note备注，也就是选择日期后，daily表里显示自己已经填过的任务
        :param date:
        :return:
        """
        data_list=[]
        note=''
        time_connect, time_cursor = self._init_taskprogress_db()
        sql="select color,date,id,project_shortname,r_id,task_type,artist,start_date,end_date,show_workhour,workhour,department,show_name," \
            "note,worktime,assigned_score,workhour_score,client_worktime,pass_task from daily where artist='{}' and date='{}'".format(self.artist,date)
        note_sql="select note from note where artist='{}' and date='{}'".format(self.artist,date)
        try:
            time_cursor.execute(sql)
            result=time_cursor.fetchall()
            if result:
                for i in result:
                    data={}
                    data['color']=i[0]
                    data['date']=i[1]
                    data['id']=i[2]
                    data['project_shortname']=i[3]
                    data['r_id']=i[4]
                    data['task_type']=i[5]
                    data['artist']=i[6]
                    data['start_date']=i[7]
                    data['end_date']=i[8]
                    data['show_workhour']=i[9]
                    data['workhour']=i[10]
                    data['department']=i[11]
                    data['show_name']=i[12]
                    data['note']=i[13]
                    data['worktime']=i[14]
                    data['assigned_score']=i[15]
                    data['workhour_score']=i[16]
                    data['client_worktime'] = i[17]
                    data['pass_task']=i[18]
                    data['status'] = ''  # 通用状态字段添加
                    data['client_status_retake_count'] = 0  # 自定义任务默认客户返修次数为0
                    data_list.append(data)
            # 查询note
            time_cursor.execute(note_sql)
            note_result=time_cursor.fetchone()
            if note_result:
                note=note_result[0]

        except Exception as get_current_daily_tasks_ERR:
            print('get_current_daily_tasks_ERR:',str(get_current_daily_tasks_ERR))
        finally:
            time_connect.close()
        return data_list,note

    def get_noworktime_tasks(self,half_month_data):
        """
        根据前半个月的数据，与本地daily数据库中的数据进行对比，然后显示出daily中没有的以及有但是工时为0同时又不是passtask类型的
        这里有2个大条件，一个是本地daily里的r_id有数据
        :param half_month_data:
        :return:
        """
        data_list = []
        # print('get_noworktime_tasks 00')
        if half_month_data:
            # print('get_noworktime_tasks 01')
            r_id_list=[]   #转成字符串类型的r_id列表，用来查询本地daily有该r_id的任务，以及用来过滤没有记录的任务
            for i in half_month_data:
                r_id=i['r_id']
                r_id_list.append(str(r_id))
            connect_r_id='|'.join(r_id_list)
            # print('connect_r_id:',connect_r_id)
            time_connect, time_cursor = self._init_taskprogress_db()
            # sql="select color,date,id,project_shortname,r_id,task_type,artist,start_date,end_date,show_workhour," \
            #     "workhour,department,show_name,note,worktime,assigned_score,workhour_score,client_worktime,pass_task" \
            #     " from daily where artist='{}'  and cast(r_id as character varying) similar to '({})' and worktime !='0' " \
            #     " and (pass_task = 1 or pass_task is null) ".format(self.artist,connect_r_id)
            sql = "select id,r_id,task_type,artist,start_date,end_date,show_workhour,workhour,department,show_name,note,color,worktime,project_shortname,date," \
                  "client_worktime,assigned_score,workhour_score,pass_task" \
                  " from daily where artist='{}' and cast(r_id as character varying) similar to '({})' ".format(self.artist, connect_r_id)

            try:
                time_cursor.execute(sql)
                result=time_cursor.fetchall()
                if result:
                    print('查到有无工时任务')
                    noworktime_tasks=[]  #查询到的在前半个月里的任务，且worktime为0并且不是passtask类型的任务
                    result_r_id_list=[]
                    for i in result:
                        # print(i)
                        data={}
                        data['id'] = i[0]
                        # if data['id']==50:
                        #     print(i)
                        data['r_id'] = i[1]

                        data['task_type'] = i[2]
                        data['artist'] = i[3]
                        data['start_date'] = i[4]
                        data['end_date'] = i[5]
                        data['show_workhour'] = i[6]
                        data['workhour'] = i[7]
                        data['department'] = i[8]
                        data['show_name'] = i[9]
                        data['note'] = i[10]
                        data['color'] = i[11]
                        data['worktime'] = i[12]
                        data['project_shortname'] = i[13]
                        data['date']= i[14]
                        data['client_worktime']= i[15]
                        data['assigned_score']= i[16]
                        data['workhour_score']= i[17]
                        data['pass_task']=  i[18] if i[18] else 0
                        data['status']='Wait'  #本地daily没有存入status,已通用Wait状态来显示项目演示
                        result_r_id_list.append(str(data['r_id']))
                        # print('看看：',data['worktime'],data['pass_task'])
                        if data['worktime'] =='0' and data['pass_task']!=1:
                            # print('已存任务但worktime为空:',data)
                            noworktime_tasks.append(data)
                    # for n in noworktime_tasks:
                    #     if n['id']==50:
                    #         print('zhao50',n)
                    #获取遗忘任务
                    not_save_in_daily_tasks=[]  #没有存储到本地daily日志中的任务，也就百分百是遗忘任务，
                    # 这里包括放假这些无工时任务。无工时任务都要记录本地daily里
                    for hd in half_month_data:
                        rid=str(hd['r_id'])
                        if rid not in result_r_id_list:
                            not_save_in_daily_tasks.append(hd)
                    # clear_task=list(set(not_save_in_daily_tasks))
                    print('还没登记的任务数量:',len(not_save_in_daily_tasks),not_save_in_daily_tasks)
                    # for u in not_save_in_daily_tasks:
                    #     print(u)
                    print('登记了忘记填时间的任务数量(不包含今天任务):',len(noworktime_tasks))
                    data_list=not_save_in_daily_tasks+noworktime_tasks
            except Exception as get_noworktime_tasks_ERR:
                print('get_noworktime_tasks_ERR:',str(get_noworktime_tasks_ERR))
            finally:
                time_connect.close()
        return data_list

    def _open_project_window(self):
        """
        打开项目窗口
        :return:
        """
        try:
            self.project_window=ProjectWindow()
            self.project_window.database_Signal.connect(self._get_project_info)
            self.project_window.show()
        except Exception as open_project_window_ERR:
            print('open_project_window_ERR:',str(open_project_window_ERR))

    def _get_project_info(self,data):
        if data:
            print('_get_project_info:',data)
            self.project_data=data
            # self.project_select_btn.setText(data['full_name']+'('+data['entity_name']+')')
            # self.project_btn.setText(data['entity_name'])
            # self.project_btn.setText(data['full_name']+'('+data['entity_name']+')')
            self.project_btn.setText(data['entity_name']+'('+self.project_map[data['entity_name']]+')')

    def _task_edited(self,text):
        if not text:
            self.my_task_list.show_all()

    def _filter_my_task(self):
        """
        搜索内容
        :return:
        """
        text=self.my_task_edit.text()
        if text:
            self.my_task_list.filter_item(text)

    def _add_daily_task(self,data_list):
        """
        槽函数,从今日任务或者我的任务列表中发送来的任务数据
        :param data_list:
        :return:
        """
        if data_list:
            self.task_list.add_tasks(data_list)

    def get_all_hour(self):
        """
        当点击任务item的时候，显示总工时，超过12小时变红
        :return:
        """
        worktimes=0
        data=self.task_list.get_all_data()
        # print(data)
        if data:
            for i in data:
                worktime=i['worktime']
                worktimes+=float(worktime)

        print('所有item times：',worktimes)
        return worktimes

    def _set_total_label(self,worktimes):
        if worktimes>12:
            self.total_count_label.setText(str(worktimes))
            self.total_count_label.setStyleSheet('color: red')
        else:
            self.total_count_label.setText(str(worktimes))
            self.total_count_label.setStyleSheet('color: black')

    def _show_info(self,data):
        """
        槽函数,当前daily或者无时长任务中点击任务的信息,重置面板属性,

        :param data:
        :return:
        """
        print('_show_data_info:', data)
        # print('keys:', data.keys())
        worktimes=self.get_all_hour()
        self._set_total_label(worktimes)
        try:
            if data:
                self.current_item=data['item']
                project=data['project_shortname']
                # database=data['database']
                date=data['date']
                print('点击任务的填写日期:',date)


                self.item_date.setText(date)
                show_project_name=project+'('+self.project_map[project]+')' if project else 'NoProject(非制作项目)'
                worktime=data['worktime'] if 'worktime' in data.keys() else '0'
                task_note_text=data['task_note_text'] if 'task_note_text' in data.keys() else ''
                self._set_passtask(data['pass_task'])   #设置passtask状态
                self.project_btn.setText(show_project_name)
                show_workhour=data['show_workhour']
                r_id=data['r_id']
                all_worktime=self.r_id_tasks_map[r_id] if self.r_id_tasks_map[r_id] else 0
                self.taskprogress_assigned.setText(show_workhour)
                self.taskprogress_submitted.setText(str(all_worktime))
                self.worktime_edit.setText(worktime)
                self.task_note_text.setText(task_note_text)
                self.assigned_score=data['assigned_score']
                self.workhour_score=data['workhour_score']
                self._set_score(self.assigned_btns,int(self.assigned_score))
                self._set_score(self.workhour_btns,int(self.workhour_score))


        except Exception as _show_info_ERR:
            print('_show_info_ERR:',str(_show_info_ERR))

    def _worktime_edited(self,text):
        self._confirm()
    def _pass_task_changed(self):
        if self.passtask.isChecked():
            self.worktime_edit.setEnabled(False)
        else:
            self.worktime_edit.setEnabled(True)
        self._confirm()

    def _confirm(self):
        """
        确认当前今日进度所选择任务的信息,并将填写的数据存入item的data里
        :return:
        """
        try:
            text=self.project_btn.text()
            project=text.split('(')[0]
            worktime=self.worktime_edit.text()
            pass_task=1 if self.passtask.isChecked() else 0
            task_note_text=self.task_note_text.toPlainText()
            data=self.current_item.data(5)
            data['project_shortname']=project
            data['worktime']=worktime
            data['pass_task'] = pass_task
            data['task_note_text']=task_note_text
            data['assigned_score']=self.assigned_score
            data['workhour_score']=self.workhour_score
            data['date']=self.item_date.text()
            # self.task_list.update_item_data(data)
            self.current_item.setData(5,data)
            text='{} | {} | {}'.format(data['date'], data['show_name'] ,data['worktime'])
            text=text[:21]+'\n'+text[21:]
            self.current_item.setText(text)
            #更新总工时
            worktimes = self.get_all_hour()
            self._set_total_label(worktimes)
            print('更新总工时',worktimes)

        except Exception as _confirm_ERR:
            print('_confirm_ERR:',str(_confirm_ERR))


    def _submit(self):
        """
        提交信息
        :return:
        """
        try:
            #获取今日提交的所有数据
            all_today_data_list = self.task_list.get_no_zero_data()
            #获取所有无时长列表里的已填写过的任务
            all_noworktime_data_list=self.zero_task_list.get_no_zero_data()
            # print('all_noworktime_data_list:',all_noworktime_data_list)
            all_task=all_today_data_list+all_noworktime_data_list
            today_assinged_tasks_list=self.today_task_list.get_all_data()  #今日安排任务,是当前选择的日期任务
            # print('today_tasks:',today_assinged_tasks_list)
            # print('all_today_data_list:',all_today_data_list)
            today_assigned_data={}
            if today_assinged_tasks_list:
                for t in range(len(today_assinged_tasks_list)):
                    today_assigned_data[str(t)]=today_assinged_tasks_list[t]
            # print('today_assigned_data:',today_assigned_data)

            all_today_data={}  # 将今日列表任务转成字典形式 {'0':{data},'1':{data}}
            if all_today_data_list:
                for a in range(len(all_today_data_list)):
                    all_today_data[str(a)]=all_today_data_list[a]
            # print('all_today_data:', all_today_data)

            date_note = self.note_text.toPlainText()
            # print('date_note:', date_note)
            #保存今日分配与提交任务信息，每日提交每日记录，如果不提交？
            if all_task or date_note:
                print('all_data_list:',all_task)
                note_data={}
                # if date_note:  #记录空的吧，就为记录人名与日期
                note_data['artist']=self.artist
                note_data['department']=self.department
                note_data['date']=self.date
                note_data['note']=date_note
                done=self.save_data(all_task,note_data,json.dumps(today_assigned_data),json.dumps(all_today_data))
                self._update_all()
                if done:
                    QMessageBox.information(self,'提示','提交成功')
                    if not self.zero_task_list.check_notime_item():  #当为空返回时，表示无时长任务都填写了
                        self.close()
                else:
                    QMessageBox.information(self, '提示', '提交失败')
            else:
                QMessageBox.information(self, '提示', '若任务时长为空,请备注提交')
        except Exception as _submit_ERR:
            print('_submit_ERR:',str(_submit_ERR))

    def _update_all(self):
        self.task_list.clear()  #清空daily原任务列表
        try:
            data_list=self.get_alltask_by_date(self.artist,self.date) #仅排期系统数据 ：前后15天所有数据
            self.my_task_list.init_new_data(data_list)  #初始化我的一个月任务
            self.r_id_tasks_map=self.get_allSavedTask_by_oneMonthtask(data_list)
            half_month_tasks=self.get_15_data(data_list,self.date)
            today_data_list=self.get_current_date_tasks(self.date,data_list) #筛选今日任务信息
            self.today_task_list.init_new_data(today_data_list)  #更新今日任务显示
            daily_task,note=self.get_current_daily_tasks(self.date)   #获取今日已经存入的任务信息
            self.task_list.init_daily_data(daily_task)  #初始化daily表,显示今日已填过的任务信息
            forget_tasks=self.get_noworktime_tasks(half_month_tasks)#获取今日及前半个月没有填工时的任务信息
            self.zero_task_list.init_new_data(forget_tasks) #显示没有填工时的任务

            self.note_text.setText(note)
        except Exception as _test_ERR:
            print('_test_ERR:',str(_test_ERR))

    def save_data(self,task_data_list,note_data,today_assigned_data,all_today_data):
        """
        将当前数据存入数据库
        :param task_data_list:
        :param note_data:
        :param today_assigned_data:
        :param all_today_data:
        :return:
        """
        done=False
        if task_data_list or note_data:

            try:
                time_connect, time_cursor = self._init_taskprogress_db()
                for task in task_data_list:
                    u_id=str(task['r_id'])+task['date']
                    select_sql="select id from daily where r_id={} and date='{}'".format(task['r_id'],task['date'])
                    time_cursor.execute(select_sql)
                    result=time_cursor.fetchone()
                    sql="insert into daily(color,project_shortname,r_id,task_type,artist,date,start_date,end_date," \
                        "show_workhour,workhour,department,show_name,note,worktime,assigned_score,workhour_score,pass_task) values ('{0}','{1}','{2}','{3}','{4}'," \
                        "'{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}',{16})".format(task['color'],task['project_shortname'],
                        task['r_id'],task['task_type'],task['artist'],task['date'],task['start_date'],task['end_date'],
                        task['show_workhour'],task['workhour'],task['department'],task['show_name'],task['note'],
                        task['worktime'],task['assigned_score'],task['workhour_score'],task['pass_task'])

                    if result:  #当存在该数据时
                        print('存在该数据',result[0])
                        sql = "update daily set color='{0}',project_shortname='{1}',r_id='{2}',task_type='{3}',artist='{4}'," \
                              "date='{5}',start_date='{6}',end_date='{7}',show_workhour='{8}',workhour='{9}',department='{10}'," \
                              "show_name='{11}',note='{12}',worktime='{13}',assigned_score='{14}',workhour_score='{15}',pass_task={16} where id ='{17}'".format(
                            task['color'], task['project_shortname'],task['r_id'], task['task_type'], task['artist'],
                            task['date'], task['start_date'],task['end_date'],task['show_workhour'], task['workhour'],
                            task['department'], task['show_name'],task['note'],task['worktime'], task['assigned_score'],
                            task['workhour_score'], task['pass_task'],result[0])#task['id'])
                        # print('update:', sql)
                    time_cursor.execute(sql)

                #记录当日备注，当日安排与提交任务
                # if note_data:
                # print('note_data:',note_data),
                search_sql="select id from note where artist ='{}' and date='{}'".format(note_data['artist'],note_data['date'])  #如果查询到表示该任务是存在的，只需要更新
                time_cursor.execute(search_sql)
                result=time_cursor.fetchone()
                note_sql="insert into note(artist,department,date,note,assigned_tasks,submit_tasks) values" \
                         " ('{0}','{1}','{2}','{3}','{4}','{5}')".format(note_data['artist'],note_data['department'],note_data['date'],
                                                                   note_data['note'],today_assigned_data,all_today_data)
                if result:
                    # print('result:',result)
                    note_id=result[0]

                    note_sql="update note set note='{}', assigned_tasks='{}',submit_tasks='{}' where id ={}".format(note_data['note'],today_assigned_data,all_today_data,note_id)
                time_cursor.execute(note_sql)
                time_connect.commit()
                done=True
            except Exception as save_data_ERR:
                print('save_data_ERR:',str(save_data_ERR))
            finally:
                time_connect.close()
        return done

    def _delete_task(self,delete_taskid_list):
        """
        槽函数,从daily list中删除的已经分配后有id的任务,防止多次删除又添加,出现重复
        :param delete_taskid_list:
        :return:
        """
        if delete_taskid_list:
            print('delete_taskid_list:',delete_taskid_list)
            time_connect, time_cursor = self._init_taskprogress_db()
            try:
                for i in delete_taskid_list:
                    sql = "delete from daily where id ={}".format(i)
                    time_cursor.execute(sql)
                time_connect.commit()
            except Exception as _delete_task_ERR:
                print('_delete_task_ERR:',str(_delete_task_ERR))
            finally:
                time_connect.close()

###########评分
    def _assinged_click(self):

        sender=self.sender().text()
        # print(sender)
        index=int(sender)
        # print(index)
        for btn in self.assigned_btns:
            btn.setIcon(QIcon(self.nicon))
        for i in range(index):
            self.assigned_btns[i].setIcon(QIcon(self.yicon))
        self.assigned_score=sender
        self._confirm()

    def _workhour_click(self):

        sender=self.sender().text()
        index=int(sender)
        for btn in self.workhour_btns:
            btn.setIcon(QIcon(self.nicon))
        for i in range(index):
            self.workhour_btns[i].setIcon(QIcon(self.yicon))
        self.workhour_score=sender
        self._confirm()

    def init_toolbtn(self,layout,func):
        btn_list=[]
        for i in range(5):
            tbtn=QToolButton(self)
            tbtn.clicked.connect(func)
            tbtn.setText(str(i+1))
            tbtn.setIcon(self.yicon)
            btn_list.append(tbtn)
            layout.addWidget(tbtn)
        return btn_list

    def _set_passtask(self,passtask):
        if passtask:
            self.passtask.setChecked(True)
        else:
            self.passtask.setChecked(False)

    def _set_score(self,btn_list,score):
        for btn in btn_list:
            btn.setIcon(QIcon(self.nicon))
        for i in range(score):
            btn_list[i].setIcon(QIcon(self.yicon))

###### 快捷键


    def keyPressEvent(self, QKeyEvent):
        # print('wc')
        if QApplication.keyboardModifiers()==Qt.ShiftModifier:
            if QKeyEvent.key()==Qt.Key_F1:
                print('zzz')
                self.close()
        super(TP, self).keyPressEvent(QKeyEvent)


    # def closeEvent(self, QCloseEvent):
    #     self._submit()

# def show_window():
#     app=QApplication(sys.argv)
#     t=TP()
#     #t.show()
#     sys.exit(app.exec_())

def check():
    check_yesterday=check_today=True
    check = CheckFillin()
    check_yesterday = check._check_yesterday()
    today_check_hour=17
    hour = datetime.datetime.now().hour
    print('当前小时:',hour)
    if hour>=today_check_hour:
        check_today=check._check_totody()
    print('昨天填写:',check_yesterday)
    print('今日填写:',check_today)

    if check_today and check_yesterday:
        return True
    else:
        return False



def show_window():
    if not check():#not
        app = QApplication(sys.argv)
        try:
            t.deleteLater()
        except:
            pass
        # print('start')
        t=TP()
        #t.show()
        try:
            # print('show')
            t.show()
        except Exception as show_ERR:
            print(str(show_ERR))
            t.deleteLater()
        sys.exit(app.exec_())

def show_window_directly():
    app = QApplication(sys.argv)
    try:
        t.deleteLater()
    except:
        pass
    t = TP()
    try:
        # print('show')
        t.show()
    except Exception as show_ERR:
        print(str(show_ERR))
        t.deleteLater()
    sys.exit(app.exec_())



if __name__ == '__main__':
    #挂服务失败:sc create daily binPath= C:\timeaxis_my_task\daily.exe start= auto
    #开机启动吧 shell:startup
    #exe与该脚本放在C:\timeaxis_my_task下(PC)
    # show_window()

    # check=CheckFillin()

    # check_yesterday=check._check_yesterday()
    # check_today=check._check_totody()
    # print('昨天填写:',check_yesterday)
    # print('今日填写:',check_today)

    # par=sys.argv[1]
    # # print(par)
    # # print(type(par))
    # if par=='auto':
    #     scheduler = BlockingScheduler()
    #     scheduler.add_job(show_window, 'cron', hour=17,minute=50)
    #     # print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C    '))
    #     try:
    #         scheduler.start()
    #     except (KeyboardInterrupt, SystemExit):
    #         pass
    # elif par=='hander':
    #     show_window()


    #
    # # app = QApplication(sys.argv)
    # scheduler = BlockingScheduler()
    # scheduler.add_job(show_window, 'interval', seconds=5)
    # try:
    #     scheduler.start()
    # except (KeyboardInterrupt, SystemExit):
    #     pass
    # # sys.exit(app.exec_())

    show_window_directly()